package demo3;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class MyNumber {
    int number = 10;
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void produce() {
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("---produce---");
        lock.lock();
        try {
            condition.signalAll();
            while (true) {
                System.out.println(Thread.currentThread().getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

//        condition.signal();   // 必须放置lock块中
    }

    public void consumer1() {
        lock.lock();
        try {
            condition.await();
            while (true) {
                System.out.println(Thread.currentThread().getName());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void consumer2() {
        lock.lock();
        try {
            condition.await();
            while (true) {
                System.out.println(Thread.currentThread().getName());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
/**
 * 验证当调用condition.singal()时，等待线程是否重新获得锁
 */
public class ConditionSingle {
    public static void main(String[] args) {
        MyNumber myNumber = new MyNumber();

        new Thread(() -> {
            myNumber.produce();
        }, "A").start();

        new Thread(() -> {
            myNumber.consumer1();
        }, "B").start();

        new Thread(() -> {
            myNumber.consumer2();
        }, "C").start();
    }
}
